package com.quark.framework.ormapping;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import com.quark.data.type.QuarkPair;
import com.quark.framework.base.QuarkGenericManager;
import com.quark.framework.utility.QuarkLog;

public class QuarkOrmBaseManager extends QuarkGenericManager {

	private HashMap<String, QuarkOrmEntity> entityMap = new HashMap<String, QuarkOrmEntity>();
	private static QuarkOrmBaseManager inst = new QuarkOrmBaseManager();
	public boolean init()
	{
		return true;
	}
	
	public static QuarkOrmBaseManager getInstance()
	{
		return inst;
	}
	
	public void registerEntity(Class<? extends QuarkOrmEntity> entityClass)
	{
		String className = entityClass.getName();
		if(entityMap.containsKey(className))
		{
			QuarkLog.logError("QuarkOrmBaseManager.registerEntity: duplicate class name '" + className + "'");
			return;
		}
		try
		{
			entityMap.put(className, entityClass.newInstance());
		}
		catch(Exception e)
		{
			QuarkLog.log(e);
			e.printStackTrace();
		}
	}
	
	public String getEntityUpdateKey(Class<? extends QuarkOrmEntity> entityClass)
	{
		QuarkOrmEntity entity = getDummyEntity(entityClass);
		QuarkOrmProperty<?> updateProperty = entity.getUpdateKey();
		if(updateProperty == null)
			return null;
		return updateProperty.getName();
	}
	
	public QuarkOrmEntity getDummyEntity(Class<? extends QuarkOrmEntity> entityClass)
	{
		String name = entityClass.getName();
		QuarkOrmEntity entity = entityMap.get(name);
		if(entity != null)
			return entity;
		else
		{
			QuarkLog.logError("QuarkOrmBaseManager.QuarkOrmEntity: entity " + name + " not registered" );
			return null;
		}
	}
	
	public Class<? extends QuarkOrmEntity> getPropertyReferInfo(String srcClassName, String srcPropertyName)
	{
		if(!entityMap.containsKey(srcClassName))
		{
			QuarkLog.logError("QuarkOrmBaseManager.getPropertyReferClass: srcClass " + srcClassName + " not registered" );
			return null;
		}
		QuarkOrmEntity entity = entityMap.get(srcClassName);		
		if(!entity.hasProperty(srcPropertyName))
		{
			QuarkLog.logError("QuarkOrmBaseManager.getPropertyReferClass: srcProperty " + srcClassName + " not found on " + srcClassName );
			return null;
		}
		QuarkOrmProperty<?> property = entity.getProperty(srcPropertyName);
		if(!property.hasReferClass())
		{
			QuarkLog.logError("QuarkOrmBaseManager.getPropertyReferClass: " + srcPropertyName + " of " + srcClassName + " doesn't refer to anything" );
			return null;
		}
		
		return property.getReferClass();
	}
	
	public Integer getEntityCount()
	{
		return entityMap.size();
	}
	
	public Collection<QuarkOrmEntity> getEntities()
	{
		return entityMap.values();
	}
}
